<?php

/**
 * Auth Controller by Estrada Virtual
 * @author Cristiano Teles <cristianoteles@estradavirtual.com.br>
 *
 */
class Ev_Controller_Auth extends Ev_Controller_Action
{
    public function loginAction()
    {
        $this->_preLogin();
        if ($this->_request->isPost() && $this->_request->getPost('login')) {
            $oFilter     = new Zend_Filter_StripTags();
            $sUser       = $oFilter->filter( $this->_request->getPost('sUser') );
            $sPassword   = $oFilter->filter( $this->_request->getPost('sPassword') );
            unset($oFilter);

            $oConfIni            = new Zend_Config_Ini( APPLICATION_PATH . '/configs/module.security.ini', APPLICATION_ENV );
            $confAuth            = $oConfIni->config->auth;
            $tableName           = $confAuth->tableName;
            $identityColumn      = $confAuth->identityColumn;
            $credentialColumn    = $confAuth->credentialColumn;
            $credentialTreatment = $confAuth->credentialTreatment;

            $oAuthAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter(), $tableName, $identityColumn, $credentialColumn, $credentialTreatment);
            $oAuthAdapter->setIdentity( $sUser );
            $oAuthAdapter->setCredential( $sPassword );

            $oAuth   = Zend_Auth::getInstance();
            $oAuth->clearIdentity();
            $oResult = $oAuth->authenticate($oAuthAdapter);
            if ($oResult->isValid()) {
                $oIdentify = $oAuthAdapter->getResultRowObject(null, $credentialColumn);
                $oIdentify->sRole = $this->_getRole($oIdentify);
                //$oAuth->setStorage(new Zend_Auth_Storage_Session($confAuth->namespace));
                $oAuth->getStorage()->write($oIdentify);

                $aliasColumnName = $oConfIni->config->message->aliasColumn;
                $this->_helper->FlashMessenger->addMessage(sprintf($oConfIni->config->message->sucessLogin, $oIdentify->$aliasColumnName));
                $this->_redirect($oConfIni->config->redirect->sucessLogin);
            } else {
                $this->_helper->FlashMessenger->addMessage($oConfIni->config->message->failLogin);
                $this->_redirect($oConfIni->config->redirect->failLogin);
            }

        }
    }

    /**
     * Method call before the login action
     * @return void
     */
    protected function _preLogin()
    {
        //$this->_helper->layout()->disableLayout();
    }

    /**
     * Get the role of user
     * @param unknown_type $oIdentify
     * @return string
     */
    protected function _getRole($oIdentify)
    {
        return 'identified';
    }

    public function logoutAction()
    {
        $oConfIni = new Zend_Config_Ini( APPLICATION_PATH . '/configs/module.security.ini', APPLICATION_ENV );
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect($oConfIni->config->redirect->logout);
    }

    public function accessDenyAction()
    {
    }

}
